import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_value_notifier.dart';
import 'package:xws/res/icons.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/circle_tab_indicator.dart';
import 'package:xws/widgets/ex_value_builder.dart';
import 'package:xws/widgets/scale_tabbar.dart';
import 'package:xws/widgets/sticky_delegate.dart';

/// 筛选状态
class _FilterState {
  _FilterState({
    required this.tabIndex,
    required this.filterValue,
    required this.values,
  });

  _FilterState.init({
    this.tabIndex = 0,
    this.filterValue = 0,
    this.values,
  }) {
    values = <int>[0, 0];
  }

  int? tabIndex;

  /// 0 全市
  /// 1 5km内
  int? filterValue;
  List<int>? values;

  _FilterState copyWith({
    int? tabIndex,
    int? filterValue,
    List<int>? values,
  }) =>
      _FilterState(
        tabIndex: tabIndex ?? this.tabIndex,
        filterValue: filterValue ?? this.filterValue,
        values: values ?? this.values,
      );
}

/// 首页Tabbar
class HomeTab extends StatefulWidget {
  const HomeTab({Key? key, this.onChanged}) : super(key: key);

  @override
  _HomeTabState createState() => _HomeTabState();

  final Function(int tabIndex, int value)? onChanged;
}

class _HomeTabState extends State<HomeTab> {
  late SafeValueNotifier<_FilterState> _filter;

  @override
  void initState() {
    super.initState();
    _filter = SafeValueNotifier<_FilterState>(_FilterState.init());
  }

  /// 点击筛选
  void _onFilterChanged() {
    final List<int> values = _filter.value.values!;
    final int tabIndex = _filter.value.tabIndex!;
    final int changeTo = _filter.value.filterValue == 0 ? 1 : 0;

    values[tabIndex] = changeTo;
    _filter.value = _filter.value.copyWith(filterValue: changeTo, values: values);

    widget.onChanged?.call(tabIndex, changeTo);
  }

  /// tab切换触发
  void _onTabChanged(int tab) {
    final List<int> values = _filter.value.values!;
    final int tabIndex = _filter.value.tabIndex!;
    final int currValue = _filter.value.filterValue!;

    if (tab != tabIndex) _filter.value.tabIndex = tab;

    if (values[tab] != currValue) {
      values[tab] = currValue;
      _filter.value = _filter.value.copyWith(values: values);

      widget.onChanged?.call(tab, currValue);
    }
  }

  @override
  Widget build(BuildContext context) {
    return SliverPersistentHeader(
      pinned: true,
      delegate: StickyDelegate(
        maxHeight: kToolbarHeight,
        child: Container(
          height: kToolbarHeight,
          padding: const EdgeInsets.symmetric(
            vertical: 10,
            horizontal: 10,
          ).copyWith(right: 20),
          color: canvas(context),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[_buildTabbar, _buildFilterBox],
          ),
        ),
      ),
    );
  }

  Widget get _buildTabbar {
    return ScaleTabBar(
      onChanged: _onTabChanged,
      labelColor: theme2(context),
      labelStyle: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
      isScrollable: true,
      tabs: const <int>[0, 1]
          .map(
            (int t) => Row(
              children: <Widget>[
                Icon(
                  <IconData>[Icons.location_city_rounded, IR.friends][t],
                  size: 16,
                ),
                const SizedBox(width: 4),
                Text(<String>['附近好物', '我的关注'][t]),
              ],
            ),
          )
          .toList(),
      indicatorSize: TabBarIndicatorSize.label,
      indicator: const CircleTabIndicator(borderSide: BorderSide.none),
    );
  }

  Widget get _buildFilterBox {
    return AppBtn.noPadding(
      onTap: _onFilterChanged,
      alignment: Alignment.center,
      height: kToolbarHeight - 20,
      radius: 0,
      color: Colors.transparent,
      child: Row(
        children: <Widget>[
          Icon(
            Icons.sort_rounded,
            size: 18,
            color: black(context).withOpacity(0.5),
          ),
          const SizedBox(width: 6),
          ExValueBuilder<_FilterState>(
            valueListenable: _filter,
            builder: (_, _FilterState f, __) {
              return Text(
                f.filterValue == 0 ? '全市' : '5km内',
                style: TextStyle(
                  fontSize: 13,
                  color: black(context).withOpacity(0.5),
                  fontWeight: FontWeight.bold,
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
